package yxy.game.pm2.command.fortdefeat;

import yxy.cherry.battle.module.record.result.BattleResult;
import yxy.cherry.game.base.message.MessageEmitterHandler;
import yxy.cherry.game.base.message.annotation.MessageSource;
import yxy.cherry.game.base.message.annotation.MessageType;
import yxy.game.pm2.Result;
import yxy.game.pm2.command.Command;
import yxy.game.pm2.message.FortDefeatMessage;
import yxy.game.pm2.module.CurrencyHandle;
import yxy.game.pm2.module.battle.BattleHandle;
import yxy.game.pm2.module.battle.BattleModule;
import yxy.game.pm2.module.fortdefeat.FortDefeatHandle;

/** 副本过关斩将 过关斩将挑战结算 */
@MessageType(proto = Command.FortDefeatChanllengeBattleClear, classtype = FortDefeatMessage.FortDefeatChanllengeBattleClearRequest.class)
public class CMD_FortDefeatChanllengeBattleClear extends Command<FortDefeatMessage.FortDefeatChanllengeBattleClearRequest> {

	@Override
	public void execute(MessageSource messageSource, FortDefeatMessage.FortDefeatChanllengeBattleClearRequest request) {
		String playerCode = messageSource.getTag();
		String battleCode = request.getBattleCode();
//		BattleMessage.BattleType battleType = request.getBattletype();

		FortDefeatMessage.FortDefeatChanllengeBattleClearResponse.Builder response = FortDefeatMessage.FortDefeatChanllengeBattleClearResponse.newBuilder();

		BattleModule battleModule = BattleModule.get(playerCode, battleCode);
		if (battleModule.isSettled()) {
			send(messageSource, response, Result.BattleHasSettled);// 战斗已结算
			return;
		}
		if (!battleModule.isFinished()) {
			send(messageSource, response, Result.BattleIsNotFinished);// 战斗尚未结束
			return;
		}

		FortDefeatHandle handle = new FortDefeatHandle();
		if (handle.isBattling(battleModule)) {
			if (!battleModule.isSkip()) {
				send(messageSource, response, Result.BattleIsNotFinished);// 战斗尚未结束
				return;
			}
		}

		response.setInfo(new BattleHandle().battleClear(battleModule));
		battleModule.setSettled(true);

		BattleResult battleResult = battleModule.getBattleResult();
		if (!battleResult.equals(BattleResult.LEFT_WIN)) {
			battleModule.set(FortDefeatHandle.battleExpireDay);
			send(messageSource, response, Result.Success);
			return;
		}

		battleModule.getSettlement().settle();
		battleModule.set(FortDefeatHandle.battleExpireDay);

		response.addAllRewards(new CurrencyHandle().packItems(battleModule.getSettlement().reward()));

		send(messageSource, response, Result.Success);
	}

	private void send(MessageSource messageSource, FortDefeatMessage.FortDefeatChanllengeBattleClearResponse.Builder response, Result result) {
		response.setResult(result.packResult());
		MessageEmitterHandler.getInstance().send(messageSource, response.build());
	}
}